﻿using ConfigLib;
using KYJModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using thinger.CommunicationLib;
using thinger.DataConvertLib;
using ToolsLib;

namespace KYJScadaProModbusRtu
{
    public class CommomMethods
    {
        //创建全局的登录对象
        public static SysAdmin currentAdmin = null;

        //创建一个全局的设备对象
        public static ModbusRTUDevice plcDevice;

        //创建一个全局的通讯对象
        public static ModbusRTU plc = new ModbusRTU();

        //创建一个全局的配置对象
        public static SysConfig sysConfig = new SysConfig();

        //创建一个全局的连接状态
        public static bool connectState = false;

        //滴答次数
        public static int tickCount = 0;

        #region 日志信息
        /// <summary>
        /// 写入系统日志
        /// </summary>
        /// <param name="isError">是否为错误信息</param>
        /// <param name="info">日志信息</param>
        public static void AddLog(bool isError, string info)
        {
            //调用委托
            if (AddLogDelegate != null)
            {
                AddLogDelegate(isError, info);
            }
        }
        /// <summary>
        /// 写入操作日志
        /// </summary>
        /// <param name="isError"></param>
        /// <param name="info"></param>
        public static void AddOPLog(bool isError, string info)
        {
            //调用委托
            if (AddLogDelegate != null)
            {
                AddOPLogDelegate(isError, info);
            }
        }

        //创建委托
        public static Action<bool, string> AddLogDelegate;
        public static Action<bool, string> AddOPLogDelegate;
        #endregion

        #region 读取配置文件
        public static void GetSysConfig()
        {
            try
            {
                sysConfig.AutoStart = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "开机自动启动", "false"));
                sysConfig.AutoLogin = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "启动自动登录", "false"));
                sysConfig.AutoLock = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "无操作自动锁屏", "false"));
                sysConfig.LockPeriod = Convert.ToInt32(IniConfigHelper.ReadIniData("配置信息", "锁屏间隔时间", "false"));
                sysConfig.ShowSeriesCount = Convert.ToInt32(IniConfigHelper.ReadIniData("配置信息", "曲线显示数量", "false"));
            }
            catch (Exception)
            {
                sysConfig = null;
            }
        }
        #endregion

        #region 保存配置文件
        /// <summary>
        /// 保存启动自动登录
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoStart(bool value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "开机自动启动", value.ToString());
        }
        /// <summary>
        /// 保存开机自动启动
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoLogin(bool value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "启动自动登录", value.ToString());
        }

        /// <summary>
        /// 保存无操作自动锁屏
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoLock(bool value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "无操作自动锁屏", value.ToString());
        }

        /// <summary>
        /// 保存锁屏间隔时间
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveLockPeriod(int value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "锁屏间隔时间", value.ToString());
        }

        /// <summary>
        /// 保存曲线显示数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveShowSeriesCount(int value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "曲线显示数量", value.ToString());
        }
        #endregion

        #region 通用写入方法
        public static OperateResult CommonWrite(string varName, string varValue)
        {
            //第一步找到对应的变量对象
            var variable = plcDevice.VarList.Where(c => c.VarName == varName).FirstOrDefault();

            if (variable != null)
            {
                try
                {
                    //第二步线性转换
                    DataType dataType = (DataType)Enum.Parse(typeof(DataType), variable.VarType);

                    var result = MigrationLib.SetMigrationValue(varValue, dataType, variable.Scale.ToString(), variable.Offset.ToString());

                    if (result.IsSuccess)
                    {
                        //第三步写入PLC
                        switch (dataType)
                        {
                            case DataType.Bool:
                                return plc.WriteBool(variable.VarAddress, Convert.ToBoolean(result.Content), variable.VarAddress.Split('.').Length == 3);

                            case DataType.Byte:
                                return plc.WriteByte(variable.VarAddress, Convert.ToByte(result.Content));

                            case DataType.Short:
                                return plc.WriteShort(variable.VarAddress, Convert.ToInt16(result.Content));

                            case DataType.UShort:
                                return plc.WriteUShort(variable.VarAddress, Convert.ToUInt16(result.Content));

                            case DataType.Int:
                                return plc.WriteInt(variable.VarAddress, Convert.ToInt32(result.Content));

                            case DataType.UInt:
                                return plc.WriteUInt(variable.VarAddress, Convert.ToUInt32(result.Content));

                            case DataType.Float:
                                return plc.WriteFloat(variable.VarAddress, Convert.ToSingle(result.Content));

                            case DataType.Double:
                                return plc.WriteDouble(variable.VarAddress, Convert.ToDouble(result.Content));

                            case DataType.Long:
                                return plc.WriteLong(variable.VarAddress, Convert.ToInt64(result.Content));

                            case DataType.ULong:
                                return plc.WriteULong(variable.VarAddress, Convert.ToUInt64(result.Content));

                            case DataType.String:
                                return plc.WriteString(variable.VarAddress, result.Content);

                            case DataType.ByteArray:
                                return plc.WriteByteArray(variable.VarAddress, ByteArrayLib.GetByteArrayFromHexString(result.Content));

                            default:
                                return OperateResult.CreateFailResult("不支持数据类型");
                        }
                    }
                    else
                    {
                        return OperateResult.CreateFailResult(result.Message);
                    }
                }
                catch (Exception ex)
                {
                    return OperateResult.CreateFailResult("写入失败：" + ex.Message);
                }
            }
            else
            {
                return OperateResult.CreateFailResult("该变量名不存在，请检查");
            }
        }
        #endregion
    }
}
